#include <string>
#include <vector>
#include <cmath>
#include "matplotlibcpp.h"

using namespace std;
namespace plt = matplotlibcpp;

// class truncated_ftn {
//     public:
//     private:
        
// };

double t_ftn(int degree, vector<double> t_divided, double x) {
    int n = t_divided.size();
    vector<double> d_diff(n);
    for (int i=0; i<n; i++) {
        if (t_divided[i]-x>=0) {
            d_diff[i] = pow(t_divided[i]-x,degree);
        } else {
            d_diff[i] = 0;
        }
    }

    for (int level = 1; level < n; ++level) {
        for (int i = n - 1; i >= level; --i) {
            d_diff[i] = (d_diff[i] - d_diff[i - 1]) / (t_divided[i] - t_divided[i - level]);
        }
    }
    
    return d_diff.back();
}

// double cardinal_basic_ftn(){

// }

int main () {
    std::cout << "----- running F -----" << std::endl;

    //B_i^n(x) = (t_{i+n} - t_{i-1})[t_{i-1},...,t_{i+n}](t-x)_{+}^n

    vector<double> knots = {0,1,2,3};
    vector<double> xData;
    int n = knots.size();
    double current = -1;
    while (current <= 4) {
        xData.push_back(current);
        current += 0.01;
    }
    plt::figure_size(1200, 700);
    plt::title("figure of n=2 truncated function");
    for (int i=0; i<n; i++) {
        for (int j=i; j<n; j++) {
            vector<double> y;
            vector<double> sub_knots(knots.begin()+j-i,knots.begin()+j+1);
            for (double t : xData) {
                y.push_back(t_ftn(2, sub_knots, t));    
            }
            plt::subplot(n, n, n*j+i+1);
            plt::plot(xData,y);
        }
    }
    plt::save("../figure/F_2.png");

    knots = {0,1,2};
    xData.clear();
    n = knots.size();
    current = -1;
    while (current <= 3) {
        xData.push_back(current);
        current += 0.01;
    }
    plt::figure_size(1200, 700);
    plt::title("figure of n=1 truncated function");
    for (int i=0; i<n; i++) {
        for (int j=i; j<n; j++) {
            vector<double> y;
            vector<double> sub_knots(knots.begin()+j-i,knots.begin()+j+1);
            for (double t : xData) {
                y.push_back(t_ftn(1, sub_knots, t));    
            }
            plt::ylim(0.0,1.1);
            plt::subplot(n, n, n*j+i+1);
            plt::plot(xData,y);
        }
    }
    plt::save("../figure/F_1.png");

    std::cout << "----- complete F -----" << std::endl;
}